package sunyu.toolkit.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * 执行脚本工具类
 *
 * @author 孙宇
 */
public class ShellKit {

    private static final Logger logger = LoggerFactory.getLogger(ShellKit.class);


    /**
     * 执行命令
     *
     * @param cmdArray 命令列表
     * @return 是否执行完成
     */
    public static boolean exec(String[] cmdArray) {
        logger.debug("调用脚本：{}", JsonKit.toJson(cmdArray));
        boolean b = false;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmdArray);

            try (InputStreamReader ir = new InputStreamReader(process.getInputStream()); LineNumberReader input = new LineNumberReader(ir);) {
                String line;
                while ((line = input.readLine()) != null) {
                    if (StringKit.isNotBlank(line)) {
                        logger.debug("{}", line);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(ExceptionKit.getStackTrace(e));
            }

            process.waitFor();
            int i = process.exitValue();  //接收执行完毕的返回值
            if (i == 0) {
                b = true;
            }
            process.destroy();  //销毁子进程
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionKit.getStackTrace(e));
        }
        return b;
    }

}
